package com.xunwulian.web.util;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.xunwulian.base.entity.Menu;

import java.math.BigInteger;
import java.util.List;

/**
 * 权限计算帮助类
 */
public class RightsHelper {
    /**
     * 利用BigInteger对权限进行2的权的和计算
     *
     * @param rights int型权限编码数组
     * @return 2的权的和
     */
    public static BigInteger sumRights(int[] rights) {
        BigInteger num = new BigInteger("0");
        for (int i = 0; i < rights.length; i++) {
            num = num.setBit(rights[i]);
        }
        return num;
    }

    /**
     * 利用BigInteger对权限进行2的权的和计算
     *
     * @param rights String型权限编码数组
     * @return 2的权的和
     */
    public static BigInteger sumRights(String[] rights) {
        BigInteger num = new BigInteger("0");
        for (int i = 0; i < rights.length; i++) {
            num = num.setBit(Integer.parseInt(rights[i]));
        }
        return num;
    }

    /**
     * 测试是否具有指定编码的权限
     *
     * @param sum
     * @param targetRights
     * @return
     */
    public static boolean testRights(BigInteger sum, int targetRights) {
        return sum.testBit(targetRights);
    }

    /**
     * 测试是否具有指定编码的权限
     *
     * @param sum
     * @param targetRights
     * @return
     */
    public static boolean testRights(String sum, int targetRights) {
        if (StringUtils.isEmpty(sum))
            return false;
        return testRights(new BigInteger(sum), targetRights);
    }

    /**
     * 测试是否具有指定编码的权限
     *
     * @param sum
     * @param targetRights
     * @return
     */
    public static boolean testRights(String sum, String targetRights) {
        if (StringUtils.isEmpty(sum))
            return false;
        return testRights(new BigInteger(sum), targetRights);
    }

    /**
     * 测试是否具有指定编码的权限
     *
     * @param sum
     * @param targetRights
     * @return
     */
    public static boolean testRights(BigInteger sum, String targetRights) {
        return testRights(sum, Integer.parseInt(targetRights));
    }

    /**
     * 更新菜单权限
     * @param roleRights
     * @param menuList
     */
    public static void updateMenuRights(String roleRights, List<Menu> menuList) {
        if (org.apache.commons.lang3.StringUtils.isNotBlank(roleRights)) {
            for (Menu menu : menuList) {
                menu.setHasMenu(RightsHelper.testRights(roleRights, menu.getMENU_ID()));
                if (menu.isHasMenu()) {
                    List<Menu> subMenuList = menu.getSubMenu();
                    for (Menu sub : subMenuList) {
                        sub.setHasMenu(RightsHelper.testRights(roleRights, sub.getMENU_ID()));
                    }
                }
            }
        }
    }
}
